from flask import Flask, make_response, jsonify, g, current_app as app
from flask_sqlalchemy import SQLAlchemy
import logging
from flask_httpauth import HTTPTokenAuth
from eim.config import Config
from flask_cors import *
import jwt
from flask_apscheduler.scheduler import APScheduler

# 数据库实例

db = SQLAlchemy()
# token 持有者
tokenScheme = "EIM"
auth = HTTPTokenAuth(scheme=tokenScheme)
ALLOWED_EXTENSIONS = {}

currentUser = {"userno": "", "username": ""}
scheduler = APScheduler()


@auth.verify_token
def verify_token(token):
    try:
        s = jwt.decode(token, app.secret_key, algorithms=['HS256'])
        return s["data"]
    except Exception as err:
        print(err)
        return False


# 根据token获取负载信息
def getPlayDataByToken(token):
    playLoad = jwt.decode(token, secret_key, ['HS256'])["data"]
    return playLoad


# 任务调度执行函数轮询
def unlock():
    try:
        with scheduler.app.app_context():
            from eim.Services.schedulerService import SchedulerService
            #sobj = SchedulerService()
            #res = sobj.unlockAllUser()
            #print(res)
    except Exception as err:
        with scheduler.app.app_context():
            app.logger.info(str(err))


# 任务调度执行函数任务触发
def cronTask():
    try:
        with scheduler.app.app_context():
            from eim.Services.schedulerService import SchedulerService
            sobj = SchedulerService()
            res = sobj.unlockAllUser()
            print(res)
    except Exception as err:
        with scheduler.app.app_context():
            app.logger.info(str(err))


def create_app():
    global secret_key
    global ALLOWED_EXTENSIONS
    global scheduler
    app = Flask(__name__)
    app.config.from_object(Config())
    ALLOWED_EXTENSIONS = app.config.get("ALLOWED_EXTENSIONS")
    # app.secret_key = app.config.get("SECRET_KEY")
    secret_key = app.config.get("SECRET_KEY")
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)  # Log等级总开关
    log_file_abs = "EIM.log"

    stream_handler = logging.StreamHandler()  # 日志控制台输出
    handler = logging.FileHandler(log_file_abs, mode='w', encoding='UTF-8')  # 日志文件输出
    handler.setLevel(logging.DEBUG)

    # 控制台输出格式
    stream_format = logging.Formatter("%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s")

    # 文件输出格式
    logging_format = logging.Formatter(
        '%(asctime)s - %(pathname)s - %(funcName)s - %(lineno)s - %(levelname)s: %(message)s')

    handler.setFormatter(logging_format)  # 为改处理器handler 选择一个格式化器
    stream_handler.setFormatter(stream_format)

    logger.addHandler(handler)  # 为记录器添加 处理方式Handler
    logger.addHandler(stream_handler)
    app.logger = logger
    # 从app的配置中读取sqlalchemy的配置
    db.init_app(app)
    scheduler.init_app(app)
    scheduler.start()
    app.scheduler = scheduler

    # 注册操作员管理蓝图
    """from IEmoniterServer.Controller.userinfoController import userBluePrint
    app.register_blueprint(userBluePrint)"""

    # 注册员工操作蓝图
    from eim.blueprints.useBluePrint import userbp
    app.register_blueprint(userbp)
    
    # 注册系统级蓝图
    from eim.blueprints.sysBluePrint import sysbp
    app.register_blueprint(sysbp)
    # 注册报表蓝图 
    from eim.blueprints.reportBluePrint import reportbp
    app.register_blueprint(reportbp)
    # 注册项目信息维护蓝图
    from eim.blueprints.projectBluePrint import prjbp
    app.register_blueprint(prjbp)
    # 注册角色信息维护蓝图
    from eim.blueprints.roleBluePrint import rolebp
    app.register_blueprint(rolebp)
    
    # 注册系统功能维护蓝图
    from eim.blueprints.powerBluePrint import powerbp
    app.register_blueprint(powerbp)
    
    # 注册网络日志操作类蓝图
    from eim.blueprints.netcomlogBluePrint import nclog
    app.register_blueprint(nclog)
    
    # 注册网络设备日志规则分析蓝图
    from eim.blueprints.netanalysisruleBluePrint import narule
    app.register_blueprint(narule)
    
    # 注册用户自定义窗体维护操作蓝图
    from eim.blueprints.userformBluePrint import userformbp
    app.register_blueprint(userformbp)

    # 注册用户自定义窗体的字段维护蓝图
    from eim.blueprints.userformFieldBluePrint  import uffieldbp
    app.register_blueprint(uffieldbp)
    
    from eim.blueprints.dataSetBluePrint import dataSetBluePrint
    app.register_blueprint(dataSetBluePrint)
    
    from eim.blueprints.doctypeBluePrint import doctypebp
    app.register_blueprint(doctypebp)
    
    CORS(app, supports_credentials=True)
    return app

    